package com.example.saiaadmin.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
public class JwtUtil {
    public static final long JWT_TTL = 60 * 60 * 1000L * 2; // 有效2小时天
    public static final String JWT_KEY = "saijwtkey";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    public static SecretKey generalKey() {
        byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        return new SecretKeySpec(encodeKey, 0, encodeKey.length, "HmacSHA256");
    }
    public static String createJWT(Map<String, Object> claims) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();

        long expMillis = nowMillis + JwtUtil.JWT_TTL;;
        Date expDate = new Date(expMillis);
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .signWith(signatureAlgorithm,JWT_KEY.getBytes(StandardCharsets.UTF_8))
                .setExpiration(expDate);
        return builder.compact();
    }

    public static Claims parseJWT(String jwt) throws Exception {
        Claims claims =  Jwts.parser()
                .setSigningKey(JWT_KEY.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(jwt).getBody();
        return claims;
    }
    //public static void main(String[] args) throws Exception {
//        Map<String, Object> claims = new HashMap<>();
//        //设置令牌主题
//        claims.put("sub", "1234567890");
//        //设置令牌其他信息
//        claims.put("name", "John Doe");
//        claims.put("admin", true);
//       String token = createJWT(claims);
//       System.out.println(token);//eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImV4cCI6MTczNjg2ODA1MH0.7Ha6JK-XkRTxUy4hWw-e_A81TvZEUePIeQk4tDZZE8A
//
//        Claims claimss =  parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImV4cCI6MTczNjg2ODA1MH0.7Ha6JK-XkRTxUy4hWw-e_A81TvZEUePIeQk4tDZZE8A");
//        System.out.println(claimss.get("sub"));
//        System.out.println(claimss.get("name"));
//        System.out.println(claimss.get("admin"));
//    }
}
